from PIL import Image
import os
import glob
import ctypes
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
import favicon
from loguru import logger

ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("pickiller")


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(615, 113)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit.setObjectName("lineEdit")
        self.horizontalLayout.addWidget(self.lineEdit)
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())
        self.comboBox.setSizePolicy(sizePolicy)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.horizontalLayout.addWidget(self.comboBox)
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout.addWidget(self.pushButton_3)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "切图大师 "))
        self.pushButton.setText(_translate("MainWindow", "选择图片..."))
        self.label.setText(_translate("MainWindow", "切图数量:"))
        self.label_2.setText(_translate("MainWindow", "切图手法:"))
        self.pushButton_2.setText(_translate("MainWindow", "保存路径"))
        self.pushButton_3.setText(_translate("MainWindow", "切!!!"))


class MyWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setupUi(self)
        self.formula = []
        self.lineEdit.setEnabled(False)
        self.comboBox.setEnabled(False)
        self.pushButton_2.setEnabled(False)
        self.pushButton_3.setEnabled(False)
        self.pushButton.clicked.connect(self.choice_img)
        self.lineEdit.textChanged.connect(self.count_num)
        self.comboBox.currentIndexChanged.connect(self.pre_cut)
        self.pushButton_2.clicked.connect(self.choice_save)
        self.pushButton_3.clicked.connect(self.cut)

    def init(self):
        self.formula = []
        self.lineEdit.clear()
        self.comboBox.clear()
        self.save_path = None
        self.lineEdit.setEnabled(False)
        self.comboBox.setEnabled(False)
        self.pushButton_2.setEnabled(False)
        self.pushButton_3.setEnabled(False)

    def choice_img(self):
        file_path = QtWidgets.QFileDialog.getOpenFileName(caption="选择图片", filter='*.png;*.jpg;*.gif;*.jpeg')
        if file_path[0]:
            try:
                self.img_path = file_path[0]
                logger.info(self.img_path)
                self.lineEdit.setEnabled(True)
            except Exception as e:
                logger.error(e)
        else:
            pass

    def count_num(self):
        self.comboBox.clear()
        self.formula.clear()
        try:
            num = int(self.lineEdit.text())
            for i in range(1, num + 1):
                if num % i == 0:
                    self.formula.append((i, int(num / i)))
                else:
                    pass
            self.comboBox.setEnabled(True)
            for i in range(len(self.formula)):
                self.comboBox.addItem(f"方案{i + 1}:{self.formula[i][0]}x{self.formula[i][1]}张")
        except Exception as e:
            logger.error(e)

    def pre_cut(self):
        try:
            index = self.comboBox.currentIndex()
            self.fml = self.formula[index]
            self.pushButton_2.setEnabled(True)
        except Exception as e:
            logger.error(e)

    def choice_save(self):
        dir_path = QtWidgets.QFileDialog.getExistingDirectory(caption="选择目录")
        if dir_path:
            logger.info(dir_path)
            self.save_path = dir_path
            self.pushButton_3.setEnabled(True)
        else:
            pass

    def cut(self):
        try:
            img = Image.open(self.img_path)
            size = img.size
            width = size[0]
            height = size[1]
            hstep = int(width / (self.fml[0] + 1))
            vstep = int(height / (self.fml[1] + 1))
            prefix = os.path.basename(self.img_path).split(".")[0]
            suffix = os.path.basename(self.img_path).split(".")[1]
            for i in range(self.fml[0] + 1):
                for j in range(self.fml[1] + 1):
                    part = img.crop((i * hstep, j * vstep, int(i + 1) * hstep, int(j + 1) * vstep))
                    part.save(self.save_path + "/" + prefix + "_" + str(i) + "_" + str(j) + "_" + "." + suffix)
            msg_box = QMessageBox(QMessageBox.Warning, '切完了', '快吧!')
            msg_box.exec_()
            path = self.save_path.replace("/", "\\")
            os.system(f"start explorer {path}")
            self.init()
        except Exception as e:
            logger.error(e)


if __name__ == '__main__':
    application = QApplication(sys.argv)
    window = MyWindow()
    window.setWindowIcon(QIcon(":favicon.ico"))
    window.show()
    application.exec_()
